package org.jeecg.modules.water.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.water.entity.LwgyJointWater;
import org.jeecg.modules.water.entity.LwgyJointWaterCmd;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.entity.LwgyJointWaterMater;
import org.jeecg.modules.water.mapper.LwgyJointWaterMapper;
import org.jeecg.modules.water.service.ILwgyJointWaterConfigurationService;
import org.jeecg.modules.water.service.ILwgyJointWaterService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.water.service.ILwgyRelaxNbConnectionService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 抄表信息（水）
 * @Author: jeecg-boot
 * @Date: 2024-03-12
 * @Version: V1.0
 */
@Api(tags = "抄表信息（水）")
@RestController
@RequestMapping("/water/lwgyJointWater")
@Slf4j
public class LwgyJointWaterController extends JeecgController<LwgyJointWater, ILwgyJointWaterService> {
    @Autowired
    private ILwgyJointWaterService lwgyJointWaterService;
    @Autowired
    private ILwgyRelaxNbConnectionService lwgyRelaxNbConnectionService;
    @Autowired
    private ILwgyJointWaterConfigurationService lwgyJointWaterConfigurationService;
    @Autowired
    private ILwgyBaseApartmentService lwgyBaseApartmentService;
    @Autowired
    private LwgyJointWaterMapper lwgyJointWaterMapper;

    /**
     * 分页列表查询
     *
     * @param lwgyJointWater
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "抄表信息（水）-分页列表查询")
    @ApiOperation(value = "抄表信息（水）-分页列表查询", notes = "抄表信息（水）-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LwgyJointWater lwgyJointWater,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "ispid", required = false) String ispid,
                                   @RequestParam(name = "valvestate", required = false) String valvestate,
                                   @RequestParam(name = "curtime_begin", required = false) String curtime_begin,
                                   @RequestParam(name = "curtime_end", required = false) String curtime_end,
                                   HttpServletRequest req) {
        String type = null;
        String id = lwgyJointWater.getRoomId();
        if (oConvertUtils.isNotEmpty(id)) {
            LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentService.getById(id);
            type = lwgyBaseApartment.getType();
        }
        QueryWrapper<LwgyJointWater> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointWater, req.getParameterMap());
        if (id != null && type != null) {
            switch (type) {
                case "campus":
                    queryWrapper.eq("t.campus_id", id);
                    break;
                case "building":
                    queryWrapper.eq("t.building_id", id);
                    break;
                case "unit":
                    queryWrapper.eq("t.unit_id", id);
                    break;
                case "layer":
                    queryWrapper.eq("t.layer_id", id);
                    break;
                case "room":
                    queryWrapper.eq("t.room_id", id);
                    break;
                default:
                    break;
            }
        }
        queryWrapper.orderByDesc("create_time");
        Page<LwgyJointWater> page = new Page<LwgyJointWater>(pageNo, pageSize);
        IPage<LwgyJointWater> pageList = lwgyJointWaterService.queryJointWaterList(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param lwgyJointWater
     * @return
     */
    @AutoLog(value = "抄表信息（水）-添加")
    @ApiOperation(value = "抄表信息（水）-添加", notes = "抄表信息（水）-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LwgyJointWater lwgyJointWater) {
        lwgyJointWaterService.save(lwgyJointWater);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param lwgyJointWater
     * @return
     */
    @AutoLog(value = "抄表信息（水）-编辑")
    @ApiOperation(value = "抄表信息（水）-编辑", notes = "抄表信息（水）-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LwgyJointWater lwgyJointWater) {
        lwgyJointWaterService.updateById(lwgyJointWater);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "抄表信息（水）-通过id删除")
    @ApiOperation(value = "抄表信息（水）-通过id删除", notes = "抄表信息（水）-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        lwgyJointWaterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "抄表信息（水）-批量删除")
    @ApiOperation(value = "抄表信息（水）-批量删除", notes = "抄表信息（水）-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.lwgyJointWaterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "抄表信息（水）-通过id查询")
    @ApiOperation(value = "抄表信息（水）-通过id查询", notes = "抄表信息（水）-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        LwgyJointWater lwgyJointWater = lwgyJointWaterService.getById(id);
        if (lwgyJointWater == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(lwgyJointWater);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lwgyJointWater
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyJointWater lwgyJointWater) {
        // Step.1 组装查询条件
        QueryWrapper<LwgyJointWater> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointWater, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String type = null;
        String id = lwgyJointWater.getRoomId();
        if (oConvertUtils.isNotEmpty(id)) {
            LwgyBaseApartment lwgyBaseApartment = lwgyBaseApartmentService.getById(id);
            type = lwgyBaseApartment.getType();
        }
        if (id != null && type != null) {
            switch (type) {
                case "campus":
                    queryWrapper.eq("t.campus_id", id);
                    break;
                case "building":
                    queryWrapper.eq("t.building_id", id);
                    break;
                case "unit":
                    queryWrapper.eq("t.unit_id", id);
                    break;
                case "layer":
                    queryWrapper.eq("t.layer_id", id);
                    break;
                case "room":
                    queryWrapper.eq("t.room_id", id);
                    break;
                default:
                    break;
            }
        }
        queryWrapper.orderByDesc("create_time");
        Page<LwgyJointWater> page = new Page<LwgyJointWater>(0, 100000);
        List<LwgyJointWater> pageList = lwgyJointWaterMapper.queryJointWaterList(page, queryWrapper);

        List<LwgyJointWater> exportList = null;
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "抄表记录"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, LwgyJointWater.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("抄表记录" + "报表", "导出人:" + sysUser.getRealname(), "抄表记录"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyJointWater.class);
    }


    /**
     * 调取轻松接口手动获取抄表信息。
     */
    @AutoLog(value = "抄表信息（水）-手动获取抄表信息")
    @ApiOperation(value = "抄表信息（水）-手动获取抄表信息", notes = "抄表信息（水）-手动获取抄表信息")
    @PostMapping("/materReading")
    @ResponseBody
    public Result<?> materReading(@RequestBody LwgyJointWaterMater lwgyJointWaterMater) {
        System.out.println("lwgyJointWater:" + lwgyJointWaterMater);
        System.out.println("lwgyJointWater:" + lwgyJointWaterMater.getBuildingId());
        //通过房间信息获取设备通信码
        QueryWrapper<LwgyJointWaterConfiguration> queryWrapper = new QueryWrapper<>();
	/*	 queryWrapper.eq("campus_id",lwgyJointWaterMater.getCampusId());
		 queryWrapper.eq("building_id",lwgyJointWaterMater.getBuildingId());
		 queryWrapper.eq("unit_id",lwgyJointWaterMater.getUnitId());
		 queryWrapper.eq("layer_id",lwgyJointWaterMater.getLayerId());*/
        queryWrapper.eq("room_id", lwgyJointWaterMater.getRoomId());
        LwgyJointWaterConfiguration ljwc = lwgyJointWaterConfigurationService.getOne(queryWrapper);


        if (ljwc != null && oConvertUtils.isNotEmpty(ljwc)) {
            //需要判断是nb表还是lora表
            if ("0".equals(ljwc.getDeviceType())) {//0是nb?

                String json = lwgyRelaxNbConnectionService.getMessages(ljwc.getCommunicationCode(), lwgyJointWaterMater.getBegintime(), lwgyJointWaterMater.getEndtime());
                try {
                    log.info("收到一条抄表信息：" + json);
                    // {"code":0,"msg":"处理成功","data":[
                    // {"ispid":"2137570808","curtime":"2024-03-12 16:27:58","stationcode":null,"conter":{"curnum":"0.13","valvestate":"00","battery":"0","sensor":"0","signal":"31","readperiod":"48","readstate":"null","reversenum":"0.00","mes":null,"type":null,"alarmNum":null,"alarmTime":null,"fifthDayFrozenNum":null,"fourthDayFrozenNum":null,"thirdDayFrozenNum":null,"secondDayFrozenNum":null,"firstDayFrozenNum":null,"increments":null,"flowAlarm":null,"pressure":null}},
                    // {"ispid":"2137570808","curtime":"2024-03-12 16:21:57","stationcode":null,"conter":{"curnum":"0.13","valvestate":"01","battery":"0","sensor":"0","signal":"31","readperiod":"48","readstate":"null","reversenum":"0.00","mes":null,"type":null,"alarmNum":null,"alarmTime":null,"fifthDayFrozenNum":null,"fourthDayFrozenNum":null,"thirdDayFrozenNum":null,"secondDayFrozenNum":null,"firstDayFrozenNum":null,"increments":null,"flowAlarm":null,"pressure":null}}]}

                    Gson gson = new Gson();
                    JsonObject jsonObject = gson.fromJson(json, JsonObject.class);

                    int code = jsonObject.get("code").getAsInt();
                    String msg = jsonObject.get("msg").getAsString();
                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    System.out.println("Code: " + code);
                    System.out.println("Msg: " + msg);
                    List<LwgyJointWater> list = new ArrayList();
                    for (JsonElement element : dataArray) {
                        LwgyJointWater water = new LwgyJointWater();
                        JsonObject dataObject = element.getAsJsonObject();
                        String ispid = dataObject.get("ispid").getAsString();
                        String curtime = dataObject.get("curtime").getAsString();

                        // 其他字段的解析方式类似，根据需要取出相应字段的值

                        JsonObject conterObject = dataObject.getAsJsonObject("conter");
                        String curnum = conterObject.get("curnum").getAsString();
                        String valvestate = conterObject.get("valvestate").getAsString();
                        String battery = conterObject.get("battery").getAsString();
                        String sensor = conterObject.get("sensor").getAsString();
                        String signal = conterObject.get("signal").getAsString();
                        String readperiod = conterObject.get("readperiod").getAsString();
                        String readstate = conterObject.get("readstate").getAsString();
                        String reversenum = conterObject.get("reversenum").getAsString();

                        System.out.println("ISP ID: " + ispid);
                        System.out.println("Current Time: " + curtime);
                        System.out.println("Curnum: " + curnum);
                        System.out.println("Valve State: " + valvestate);
                        // 可以继续解析其他字段
                        water.setIspid(ispid);
                        water.setCurtime(curtime);
                        water.setCurnum(curnum);
                        water.setValvestate(valvestate);
                        water.setBattery(battery);
                        water.setSensor(sensor);
                        water.setSignalstrength(signal);
                        water.setReadperiod(readperiod);
                        water.setReadstate(readstate);
                        water.setReversenum(reversenum);
                        water.setMeterReadingType("1");//手动抄表
                        list.add(water);

                    }
                    lwgyJointWaterService.saveBatch(list);
                    return Result.OK("success");
                } catch (Exception e1) {
                    e1.printStackTrace();
                    return Result.error("nb表解析失败");
                }


            } else if ("1".equals(ljwc.getDeviceType())) {//1是lora?
                // String json = lwgyRelaxConnectionService.getMessages(ljwc.getCommunicationCode(),lwgyJointWaterMater.getBegintime(),lwgyJointWaterMater.getEndtime());
                return Result.error("lora表暂不支持手动查询");


                // return Result.OK("success");
            } else {
                return Result.error("未知的设备类型");
            }


        } else {
            return Result.error("该房间未获取到设备信息");
        }
    }
}
